package com.xunheyun.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xunheyun.mapper.ConfSyncMapper;
import com.xunheyun.service.IConfSyncService;
import com.xunheyun.utils.ConsoleUtils;
import com.xunheyun.vo.ConfigFile;
import com.xunheyun.vo.ConfigService;
import com.xunheyun.vo.HostServer;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.Session;

@Service
public class ConfSyncServiceImpl implements IConfSyncService {

	@Autowired
	private ConfSyncMapper confSyncMapper;
	
	@Override
	public String syncConfig(String configId, String hosts) {
		
		// 1. 根据配置ID获取配置的详细信息
		ConfigFile config = confSyncMapper.getConfigById(Integer.valueOf(configId));
		
		// 2. 根据主机信息获取主机的详细信息
		String[] strings = hosts.split(",");
		
		for (String serverId : strings) {
			
			// 3. 对每个主机进行配置的下发
			HostServer hostServer = confSyncMapper.getHostServer(Integer.valueOf(serverId));
			scpFile(hostServer,config);
		}
		
		return "success";
	}

	private void scpFile(HostServer hostServer,ConfigFile config){
		
		Connection connection = new Connection(hostServer.getServer_ip());
		try {
			connection.connect();
			boolean b = connection.authenticateWithPassword(hostServer.getServer_user(), hostServer.getServer_pwd());
			
			if (b) {
				//打开一个会话session，执行linux命令  
	            Session sess = connection.openSession();
	            
	            //对旧文件进行备份
	            String filename = config.getConfig_name();
	            sess.execCommand("cp " + hostServer.getConfig_dir() + "/" + filename + " " + hostServer.getConfig_dir() +"/"+filename+".bak");
	            ConsoleUtils.console(sess);
	            
	            // 将数据库内容存储为临时文件
	            String configContent = config.getConfig_content();
	            String path="/Users/HAITAO/"+filename;
	            File file=new File(path);
	            if(!file.exists()) file.createNewFile();
	            FileOutputStream out=new FileOutputStream(file,false); //如果追加方式用true        
	            out.write(configContent.getBytes("utf-8"));//注意需要转换对应的字符集
	            out.close();
	            
	            // 拷贝文件
				SCPClient scpClient = new SCPClient(connection);
				scpClient.put("/Users/HAITAO/"+filename, hostServer.getConfig_dir()+config.getFile_path());
				  
				ConsoleUtils.console(sess);
				// 删除临时文件
				//TODO
			}
			connection.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<ConfigService> configServiceList(int userId) {
		
		List<ConfigService> configServiceList = confSyncMapper.configServiceList(userId);
		
		return configServiceList;
	}

	@Override
	public String addConfigService(ConfigService configService) {
		
		configService.setConfig_service_time(new Timestamp(System.currentTimeMillis()));
		
		confSyncMapper.insertConfigService(configService);
		
		return "success";
	}

	@Override
	public String deleteConfigService(int configServiceId) {
		
		confSyncMapper.deleteConfigService(configServiceId);
		
		return "success";
	}

	@Override
	public List<ConfigFile> configFileList(int configServiceId) {
		
		return confSyncMapper.configFileList(configServiceId);
	}

	@Override
	public int saveConfigFile(String configServiceId, String content,String fileName,String configId,String filePath) {
		
		ConfigFile configFile = new ConfigFile();
		configFile.setConfig_name(fileName);
		configFile.setConfig_service_id(Integer.valueOf(configServiceId));
		configFile.setConfig_content(content);
		configFile.setConfig_id(Integer.valueOf(configId));
		configFile.setFile_path(filePath);
		
		if (configFile.getConfig_id() == -1) {
			return confSyncMapper.saveConfigFile(configFile);
		}else{
			return confSyncMapper.updateConfigFile(configFile);
		}
	}

	@Override
	public int deleteConfigFile(String configId) {
		return confSyncMapper.deleteConfigFile(Integer.valueOf(configId));
	}

	@Override
	public ConfigFile getConfigFileById(int configId) {
		
		ConfigFile configFile = confSyncMapper.getConfigFileById(configId);
		
		String content =  configFile.getConfig_content();
		content = content.replaceAll("'", "\'");
		content = content.replaceAll("\r\n", "<br>&nbsp;&nbsp;");
		content = content.replaceAll("\n", "<br>&nbsp;&nbsp;");
		
		configFile.setConfig_content(content);
		
		return configFile;
	}

	@Override
	public ConfigService getConfigServiceById(int configServiceId) {
		return confSyncMapper.getConfigServiceById(configServiceId);
	}

	@Override
	public int updateConfigService(ConfigService configService) {
		return confSyncMapper.updateConfigService(configService);
	}
}






